<!--
 * @Author: 噜噜雯雯 2199987619@qq.com
 * @Date: 2025-07-11 15:31:18
 * @LastEditors: 噜噜雯雯 2199987619@qq.com
 * @LastEditTime: 2025-07-11 17:22:47
 * @FilePath: \linePatrol\vue-element-plus-admin\src\views\Authorization\Post\post.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, reactive } from 'vue'
import { ElTag } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import Write from './components/Write.vue'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import PostApi from '@/api/post/index'
import { PostListType } from '@/api/post/type'
const { t } = useI18n()
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await PostApi.GetPostList({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.rows || [],
      total: res.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await PostApi.DeletPost(unref(ids)[0])
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'postId',
    label: '岗位编号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'postCode',
    label: '岗位编码',
    search: {
      component: 'Input',
      componentProps: {
        placeholder: '岗位编码'
      }
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'postName',
    label: '岗位名称',
    search: {
      component: 'Input',
      componentProps: {
        placeholder: '岗位名称'
      }
    },
    detail: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'postSort',
    label: '岗位排序',
    form: {
      component: 'InputNumber',
      colProps: {
        span: 20
      }
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'status',
    label: '状态',
    search: {
      component: 'Select',
      componentProps: {
        placeholder: '状态',
        options: [
          {
            value: '0',
            label: '正常'
          },
          {
            value: '1',
            label: '停用'
          }
        ]
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const status = data.row.status
          return (
            <>
              <ElTag type={status == '0' ? 'success' : 'danger'}>
                {status == '0' ? '正常' : '停用'}
              </ElTag>
            </>
          )
        }
      }
    },
    form: {
      component: 'Select',
      colProps: {
        span: 20
      },
      componentProps: {
        options: [
          {
            value: '0',
            label: '正常'
          },
          {
            value: '1',
            label: '停用'
          }
        ]
      }
    }
  },
  {
    field: 'remark',
    label: '备注',
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    },
    table: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },

  {
    field: 'createTime',
    label: '创建时间',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: '操作',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data) => {
          return (
            <>
              <span class="TableBtn" onClick={() => action(data.row, 'edit')}>
                修改
              </span>
              <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                删除
              </span>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)
const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentRow = ref<PostListType>()
const actionType = ref('')

const delLoading = ref(false)
const ids = ref<string[]>([])

const delData = async (row?: PostListType) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.postId]
    : elTableExpose?.getSelectionRows().map((v: PostListType) => v.postId) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const action = async (row: PostListType, type: string) => {
  dialogTitle.value = t(type === 'edit' ? '修改' : '添加')
  dialogVisible.value = true
  actionType.value = type
  currentRow.value = row
}
const writeRef = ref<ComponentRef<typeof Write>>()
const saveLoading = ref(false)
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res: any = ref(false)
    if (actionType.value == 'add') {
      res.value = await PostApi.AddPost(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      res.value = await PostApi.EditPost(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap class="flex-[3] ml-20px">
    <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
      <Icon icon="ep:plus" :size="12" />添加
    </BaseButton>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      row-key="postId"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" style="width: 500px">
    <Write ref="writeRef" :form-schema="allSchemas.formSchema" :current-row="currentRow" />
    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
<style scoped>
:deep(.TableBtn) {
  margin: 0 6px;
  font-size: 12px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600 !important;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
</style>
